package com.yuji.aacar.net.interceptor;

import android.text.TextUtils;

import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.net.config.BlueLog;
import com.yuji.aacar.net.config.HttpConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * <li>Package:consumer.ttpc.com.httpmodule.Interceptor </li>
 * <li>Author: yehaijian </li>
 * <li>Date: 2017/4/20 </li>
 * <li>Description: </li>
 */
public class TtpInterceptor implements Interceptor {
    private String serviceName;
    public TtpInterceptor(String serviceName) {
        this.serviceName=serviceName;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        FormBody formBody = (FormBody) original.body();
        String header = formBody.size() > 1 ? formBody.value(1) : "";
        String isWebView = formBody.size() > 1 ? formBody.value(2) : "";
        String host= HttpConfig.serviceMap.get(serviceName)!=null?((HttpConfig.ServiceInfo)HttpConfig.serviceMap.get(serviceName)).getHost():"";
        LogUtil.e("Interceptor header",header);
        LogUtil.e("Interceptor isWebView",isWebView);
        if(Boolean.valueOf(TextUtils.isEmpty(isWebView)?"false":isWebView)){
            String url=original.url().toString();
            HttpConfig.WEB_URL=url.substring(0,url.length()-1)+"?info="+(formBody.size() > 0 ? formBody.encodedValue(0) : "");
            Map map=new HashMap();
            map.put("Host",host);
            map.put("Ttp",header);
            HttpConfig.WEB_HEAD_MAP=map;
        }
        //TODO okhttp图片加载
               /* String isImage = original.header(HttpConfig.IS_IMAGE);
                if (!TextUtils.isEmpty(isImage)) {
                    if (isImage.toUpperCase().equals("TRUE")) {
                        return chain.proceed(original);
                    }
                }*/

        FormBody newBody = new FormBody.Builder().addEncoded("info", formBody.size() > 0 ? formBody.encodedValue(0) : "")
                .build();
        Request.Builder builder = original.newBuilder()
                .addHeader("Ttp", header)
                .post(newBody);

        if (!TextUtils.isEmpty(host)) {
            builder.addHeader("Host", host);
        }
        Request request = builder.build();
        BlueLog.e("http_header",request.headers().get("Host"));
        BlueLog.e("request_url", request.url() + "");
        return chain.proceed(request);
    }
}
